package zero.tech.games.gateway.config;

import java.net.URI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;

import zero.tech.games.common.UserLastRoomUtil;
import zero.tech.games.common.data.UserLastRoom;
@SuppressWarnings("deprecation")
@Component
public class WsOrHttpFilter extends LoadBalancerClientFilter{
	@Autowired
	private UserLastRoomUtil userLastRoomUtil;
	public WsOrHttpFilter(LoadBalancerClient loadBalancer, LoadBalancerProperties properties) {
		super(loadBalancer, properties);
	}
	@Override
	protected ServiceInstance choose(ServerWebExchange exchange) {
		if (this.loadBalancer instanceof RibbonLoadBalancerClient) {
			RibbonLoadBalancerClient client = (RibbonLoadBalancerClient) this.loadBalancer;
			URI url=exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
			System.out.println("url====>"+url);
			String scheme=url.getScheme();
			String serviceId = url.getHost();
			boolean checkLastRoom=false;
			//格式serverid#ip:port
			String userLastRoom=null;
			if("ws".equals(scheme)) {
				//有最后房间信息大厅也不让进
				checkLastRoom=true;
				if(checkLastRoom) {
					//进入游戏服需要检查最后房间信息
					String str=url.toString();
					String playerid=str.substring(str.lastIndexOf("/")+1);
					userLastRoom=getUserLastRoom(playerid);
				}
			}else {
				//http连接创建,拦截登陆路径进行token校验
			}
			
			if(userLastRoom!=null) {
				String server_id=userLastRoom.split("#")[0];
				Assert.isTrue(serviceId.equals(server_id),"最后房间信息和路由必须匹配,否则是非正常逻辑运行");
				String hostAndPort=userLastRoom.split("#")[1];
				return client.choose(serviceId, "BACKROOM###"+hostAndPort);
			}else {
				return client.choose(serviceId);
			}
        }
		return super.choose(exchange);
	}
	private String getUserLastRoom(String playerid) {
		UserLastRoom userLastRoom=userLastRoomUtil.getUserLastRoom(playerid);
		if(userLastRoom!=null) {
			String service_id=userLastRoom.getService_id();
			String host=userLastRoom.getHost();
			String port=userLastRoom.getPort();
			return 	service_id+"#"+host+":"+port;
		}
		return null;
	}
}
